package cn.lysy.xiaoruan.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.preference.DialogPreference;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import java.io.File;

import cn.lysy.xiaoruan.R;
import cn.lysy.xiaoruan.javabean.Result;
import cn.lysy.xiaoruan.model.UserModel;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RegActivity extends AppCompatActivity {
    private ImageButton reg_back;
    private ImageButton reg_photo;
    private EditText reg_uloginname;
    private EditText reg_uname;
    private EditText reg_password;
    private EditText reg_chpassword;
    private EditText reg_telephone;
    private EditText reg_email;
    private Button reg;

    private Call call;
    private Bitmap mBitmap;
    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    protected static Uri tempUri;
    private static final int CROP_SMALL_PICTURE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reg);
        intiview();
        setClickL();
    }

    private void setClickL() {
        reg_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(RegActivity.this,HomeActivity.class);
                startActivity(intent);
            }
        });

        reg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UserModel userModel=new UserModel();
                call=userModel.reg(reg_uloginname.getText().toString(),reg_uname.getText().toString(),
                        reg_password.getText().toString(),reg_chpassword.getText().toString(),
                        reg_telephone.getText().toString(),reg_email.getText().toString());
                Callback<Result> callback=new Callback<Result>() {
                    @Override
                    public void onResponse(Call<Result> call, Response<Result> response) {

                        Result result=response.body();
                        String s=result.getSuccess().toString();
                        if ("0".equals(s)){
                            Toast.makeText(RegActivity.this, "注册失败！", Toast.LENGTH_SHORT).show();
                        }else if ("1".equals(s)){
                            Toast.makeText(RegActivity.this, "欢迎加入我们的大家庭！", Toast.LENGTH_SHORT).show();
                        }else if ("2".equals(s)){
                            Toast.makeText(RegActivity.this, "两次密码输入不相同", Toast.LENGTH_SHORT).show();
                        }else if ("3".equals(s)){
                            Toast.makeText(RegActivity.this, "该联系电话已经注册", Toast.LENGTH_SHORT).show();
                        }else if ("4".equals(s)){
                            Toast.makeText(RegActivity.this, "该登录名称已经注册", Toast.LENGTH_SHORT).show();
                        }else if ("5".equals(s)){
                            Toast.makeText(RegActivity.this, "该邮箱已经注册", Toast.LENGTH_SHORT).show();
                        }else if ("6".equals(s)){
                            Toast.makeText(RegActivity.this, "个别信息不能为空", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result> call, Throwable t) {

                    }
                };
                call.enqueue(callback);
            }
        });

        reg_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showChoosePicDialog();
            }
        });
    }

    private void showChoosePicDialog() {
        AlertDialog.Builder builder=new AlertDialog.Builder(RegActivity.this);
        builder.setTitle("添加图片");
        String[] items={"选择本地图片","拍照"};
        builder.setNegativeButton("取消",null);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                switch (i){
                    case CHOOSE_PICTURE: // 选择本地照片
                        Intent openAlbumIntent = new Intent(
                                Intent.ACTION_GET_CONTENT);
                        openAlbumIntent.setType("image/*");
                        //用startActivityForResult方法，待会儿重写onActivityResult()方法，拿到图片做裁剪操作
                        startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
                        break;
                    case TAKE_PICTURE: // 拍照
                        Intent openCameraIntent = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        tempUri = Uri.fromFile(new File(Environment
                                .getExternalStorageDirectory(), "temp_image.jpg"));
                        // 将拍照所得的相片保存到SD卡根目录
                        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
                        startActivityForResult(openCameraIntent, TAKE_PICTURE);
                        break;
                }

            }
        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RegActivity.RESULT_OK) {
            switch (requestCode) {
                case TAKE_PICTURE:
                    cutImage(tempUri); // 对图片进行裁剪处理
                    break;
                case CHOOSE_PICTURE:
                    cutImage(data.getData()); // 对图片进行裁剪处理
                    break;
                case CROP_SMALL_PICTURE:
                    if (data != null) {
                        setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
                    }
                    break;
            }
        }
    }

    private void cutImage(Uri uri) {
        if (uri == null) {
            Log.i("alanjet", "The uri is not exist.");
        }
        tempUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        //com.android.camera.action.CROP这个action是用来裁剪图片用的
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_SMALL_PICTURE);
    }

    private void intiview() {
        reg_back= (ImageButton) findViewById(R.id.reg_back);
        reg_photo= (ImageButton) findViewById(R.id.reg_photo);
        reg_uloginname= (EditText) findViewById(R.id.uloginname);
        reg_uname= (EditText) findViewById(R.id.unmae);
        reg_password= (EditText) findViewById(R.id.upassword);
        reg_chpassword= (EditText) findViewById(R.id.check_password);
        reg_telephone= (EditText) findViewById(R.id.utelephone);
        reg_email= (EditText) findViewById(R.id.uemail);
        reg= (Button) findViewById(R.id.bt_register);
    }

    public void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            mBitmap = extras.getParcelable("data");
            //这里图片是方形的，可以用一个工具类处理成圆形（很多头像都是圆形，这种工具类网上很多不再详述）
            reg_photo.setImageBitmap(mBitmap);//显示图片
            //在这个地方可以写上上传该图片到服务器的代码，后期将单独写一篇这方面的博客，敬请期待...
        }

    }
}
